package com.eqxiu.ieditor.api.controller.mall;


import com.alibaba.fastjson.JSON;
import com.eqxiu.bigdata.statistics.api.StatisticsApi;
import com.eqxiu.common.persistence.Page;
import com.eqxiu.hd.api.HdCommonServiceApi;
import com.eqxiu.hd.dto.Activity;
import com.eqxiu.hd.dto.PageDTO;
import com.eqxiu.ieditor.api.controller.BaseApiController;
import com.eqxiu.ieditor.api.controller.BaseController;
import com.eqxiu.ieditor.commons.web.ResultData;
import com.eqxiu.ieditor.dto.WapScenceDTO;
import com.eqxiu.lp.api.LongPageServiceApi;
import com.eqxiu.lp.dto.LongPageDTO;
import com.eqxiu.lp.dto.LongPageParam;
import com.eqxiu.print.service.api.PrintServerServiceApi;
import com.eqxiu.print.service.dto.PrintDTO;
import com.eqxiu.scene.api.BaseSceneServiceApi;
import com.eqxiu.scene.dto.SceneDTO;
import com.eqxiu.scene.dto.SceneParam;
import com.eqxiu.tiny.pagination.PageForm;
import com.eqxiu.video.video.api.VideoApi;
import com.eqxiu.video.video.dto.VideoDto;
import com.eqxiu.video.video.param.VideoQueryParam;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;

/**
 * 获取我的作品
 */
@RestController
@RequestMapping("/api/wap/scence")
public class MyScenceControlelr  extends BaseController implements BaseApiController {

    Logger logger = LoggerFactory.getLogger(MyScenceControlelr.class);

    @Autowired
    private LongPageServiceApi longPageServiceApi;

    @Autowired
    private com.eqxiu.form.api.LongPageServiceApi formApi;

    @Autowired
    private BaseSceneServiceApi baseSceneServiceApi;

    @Autowired
    private StatisticsApi statisticsApi;

    @Autowired
    private HdCommonServiceApi hdCommonServiceApi;

    @Autowired
    private PrintServerServiceApi printServerServiceApi;
    @Autowired
    private VideoApi videoApi;


    @Value("${scence.page.size}")
    private Integer scencePageSize;

    @PostMapping("/myScence")
    @ResponseBody
    public ResultData getMyScence(Integer pageNo, Integer pageSize, String userId) {
        Map map  = new HashMap();
        List<WapScenceDTO> wapScenceDTOList = new ArrayList<>();
        List<WapScenceDTO>  resultList = new ArrayList<>();
        try{
            //长页
            LongPageParam pageParam = new LongPageParam();
            pageParam.setPageNo(1);
            pageParam.setPageSize(scencePageSize);
            pageParam.setUser(userId);
            int[] bizLongType = {3};
            pageParam.setBizType(bizLongType);
            //bizType传1是易表单，传3是长页面
            logger.info("长页、搜索参数-->{}", new Gson().toJson(pageParam));
            Page<LongPageDTO> longPageDTOPage = longPageServiceApi.findListByParam(pageParam);
            logger.info("长页、搜索结果-->{}", new Gson().toJson(longPageDTOPage));
            //易表单
            com.eqxiu.form.dto.LongPageParam formPageForm=new com.eqxiu.form.dto.LongPageParam();
            formPageForm.setPageNo(1);
            formPageForm.setPageSize(scencePageSize);
            formPageForm.setUser(userId);
            int[] bizFormType = {1};
            formPageForm.setBizType(bizFormType);
            logger.info("易表单搜索参数-->{}", new Gson().toJson(formPageForm));
            Page<com.eqxiu.form.dto.LongPageDTO> formDTOPage  = formApi.findListByParam(formPageForm);
            logger.info("易表单搜索结果-->{}", new Gson().toJson(formDTOPage));
            List<com.eqxiu.form.dto.LongPageDTO> formDTOPageList = formDTOPage.getList();
            List<LongPageDTO> longPageDTOList = longPageDTOPage.getList();
            SceneParam sceneParam = new SceneParam();
            sceneParam.setPageNo(1);
            sceneParam.setPageSize(scencePageSize);
            sceneParam.setUser(userId);
            logger.info("调用h5编辑器传入参数={}",new Gson().toJson(sceneParam));
            Page<SceneDTO> sceneDTOPage = baseSceneServiceApi.findSceneListPageForPc(sceneParam);
            logger.info("调用h5编辑器结果={}", JSON.toJSONString(sceneDTOPage));
            List<SceneDTO> sceneDTOList = sceneDTOPage.getList();
            logger.info("调用gc编辑器传入参数userId={}",new Gson().toJson(userId));
            PageDTO<Activity> gcScencePage =  hdCommonServiceApi.queryActivityList(userId,1,scencePageSize);
            logger.info("调用gc编辑器传出参{}",new Gson().toJson(gcScencePage));
            List<Activity> gcScenceList = gcScencePage.getDataList();
            PrintDTO printDTO = new PrintDTO();
            printDTO.setCreateUser(userId);
            logger.info("调用design编辑器传入参数printDTO={}",new Gson().toJson(printDTO));
            com.eqxiu.print.service.dto.PageDTO<PrintDTO> printDTOPageDTO = printServerServiceApi.findPrintList(1,scencePageSize,printDTO);
            logger.info("调用design编辑器传出参{}",new Gson().toJson(printDTOPageDTO));
            List<PrintDTO> printDTOList = printDTOPageDTO.getList();
            PageForm pageForm =  PageForm.create(1,scencePageSize);
            VideoQueryParam videoQueryParam = new VideoQueryParam();
            videoQueryParam.setUserId(userId);
            logger.info("调用video编辑器传出参{}",new Gson().toJson(pageForm));
            com.eqxiu.tiny.pagination.PageDTO<VideoDto> videoDtoPageDTO = videoApi.pageAndPv(pageForm,videoQueryParam);
            logger.info("调用video编辑器传出参{}",new Gson().toJson(videoDtoPageDTO));
            List<VideoDto> videoDtoList = videoDtoPageDTO.getDataList();
            for(VideoDto video:videoDtoList){
                WapScenceDTO wapScenceDTO = new WapScenceDTO();
                wapScenceDTO.setSceneCode(video.getPlayCode());
                if(null==video.getUpdateTime()){
                    wapScenceDTO.setUpdateTime(video.getCreateTime());
                }else{
                    wapScenceDTO.setUpdateTime(video.getUpdateTime());
                }
                wapScenceDTO.setSceneName(video.getTitle());
                wapScenceDTO.setSceneId(video.getId());
                wapScenceDTO.setType(5);
                wapScenceDTO.setSceneCover(video.getCoverImg());
                wapScenceDTO.setTransverse(video.getTransverse());
                if(null != video.getStatus() && 4==video.getStatus()){
                    wapScenceDTO.setStatus(1);
                }else{
                    wapScenceDTO.setStatus(0);
                }
                wapScenceDTOList.add(wapScenceDTO);
            }

            //轻设计
            for(PrintDTO print:printDTOList){
                WapScenceDTO wapScenceDTO = new WapScenceDTO();
                wapScenceDTO.setSceneCode(print.getCode());
                if(null==print.getUpdateTime()){
                    wapScenceDTO.setUpdateTime(print.getCreateTime());
                }else{
                    wapScenceDTO.setUpdateTime(print.getUpdateTime());
                }
                wapScenceDTO.setSceneName(print.getTitle());
                wapScenceDTO.setSceneId(print.getId());
                wapScenceDTO.setType(4);
                wapScenceDTO.setSceneCover(print.getCover());
                wapScenceDTO.setWidth(print.getWidth());
                wapScenceDTO.setUnit(print.getUnit());
                wapScenceDTO.setHeight(print.getHeight());
                //分享状态 创建作品默认是1（未进入审核队列）， 3 已发布（默认发布后是审核成功） 4 审核关闭（失败） 5驳回再审
                if(null !=print.getIsShare() && 3==print.getIsShare()){
                    wapScenceDTO.setStatus(1);
                }else{
                    wapScenceDTO.setStatus(0);
                }
                wapScenceDTOList.add(wapScenceDTO);
            }
            //互动
            for(Activity activity:gcScenceList){
                WapScenceDTO wapScenceDTO = new WapScenceDTO();
                wapScenceDTO.setSceneCode(activity.getCode());
                if(null==activity.getUpdateTime()){
                    wapScenceDTO.setUpdateTime(activity.getCreateTime());
                }else{
                    wapScenceDTO.setUpdateTime(activity.getUpdateTime());
                }
                wapScenceDTO.setSceneName(activity.getActivityName());
                wapScenceDTO.setSceneId(activity.getId());
                wapScenceDTO.setType(2);
                wapScenceDTO.setSceneCover(activity.getCoverKey());
                wapScenceDTO.setTemplateType(activity.getTemplateType());
                if(null!=activity.getPublishTime()){
                    wapScenceDTO.setStatus(1);
                }else{
                    wapScenceDTO.setStatus(0);
                }
                wapScenceDTOList.add(wapScenceDTO);
            }
            //长页
            for(LongPageDTO longPageDTO:longPageDTOList){
                WapScenceDTO wapScenceDTO = new WapScenceDTO();
                wapScenceDTO.setSceneId(longPageDTO.getId());
                wapScenceDTO.setSceneName(longPageDTO.getTitle());
                if(null==longPageDTO.getUpdateTime()){
                    wapScenceDTO.setUpdateTime(longPageDTO.getCreateTime());
                }else{
                    wapScenceDTO.setUpdateTime(longPageDTO.getUpdateTime());
                }
                wapScenceDTO.setSceneCode(longPageDTO.getCode());
                wapScenceDTO.setSceneCover(longPageDTO.getCover());
                if(null!=longPageDTO.getBizType()){
                    if(3!=longPageDTO.getBizType()){
                        wapScenceDTO.setType(3);
                    }else{
                        wapScenceDTO.setType(longPageDTO.getBizType());
                    }
                }
                if(null!=longPageDTO.getPublishTime()){
                    wapScenceDTO.setStatus(1);
                }else{
                    wapScenceDTO.setStatus(0);
                }
                wapScenceDTOList.add(wapScenceDTO);
            }
            //易表单
            for(com.eqxiu.form.dto.LongPageDTO formPageDTO:formDTOPageList){
                WapScenceDTO wapScenceDTO = new WapScenceDTO();
                wapScenceDTO.setSceneId(formPageDTO.getId());
                wapScenceDTO.setSceneName(formPageDTO.getTitle());
                if(null==formPageDTO.getUpdateTime()){
                    wapScenceDTO.setUpdateTime(formPageDTO.getCreateTime());
                }else{
                    wapScenceDTO.setUpdateTime(formPageDTO.getUpdateTime());
                }
                wapScenceDTO.setSceneCode(formPageDTO.getCode());
                wapScenceDTO.setSceneCover(formPageDTO.getCover());
                if(null!=formPageDTO.getBizType()){
                    if(1!=formPageDTO.getBizType()){
                        wapScenceDTO.setType(1);
                    }else{
                        wapScenceDTO.setType(formPageDTO.getBizType());
                    }
                }
                if(null!=formPageDTO.getPublishTime()){
                    wapScenceDTO.setStatus(1);
                }else{
                    wapScenceDTO.setStatus(0);
                }
                wapScenceDTOList.add(wapScenceDTO);
            }
            //H5作品
            for(SceneDTO sceneDTO:sceneDTOList){
                WapScenceDTO wapScenceDTO = new WapScenceDTO();
                wapScenceDTO.setSceneId(sceneDTO.getId());
                wapScenceDTO.setSceneName(sceneDTO.getName());
                if(null==sceneDTO.getUpdateTime()){
                    wapScenceDTO.setUpdateTime(sceneDTO.getCreateTime());
                }else{
                    wapScenceDTO.setUpdateTime(sceneDTO.getUpdateTime());
                }
                wapScenceDTO.setSceneCode(sceneDTO.getCode());
                wapScenceDTO.setSceneCover(sceneDTO.getCover());
                wapScenceDTO.setType(0);
                if(null!=sceneDTO.getPublishTime()){
                    wapScenceDTO.setStatus(1);
                }else{
                    wapScenceDTO.setStatus(0);
                }
                wapScenceDTOList.add(wapScenceDTO);
            }
            //手动分页
            resultList = dealScence(wapScenceDTOList,pageNo,pageSize);
            for(WapScenceDTO wapScenceDTO:resultList){
                //获取pv、uv、fpv
                Map params = new HashMap();
                params.put("id",wapScenceDTO.getSceneId());
                //product - 作品类型，h5/h5is=互动h5/video-视频/ls-长页面/print-轻设计
                //type 0-样例，2-互动，1-易表单，3-长页
                if(wapScenceDTO.getType()==0){
                    params.put("product","h5");
                }else if(wapScenceDTO.getType()==1 || wapScenceDTO.getType()==3){
                    params.put("product","ls");
                }else if(wapScenceDTO.getType()==2){
                    params.put("product","h5is");
                }
                Map<String, Object> mapResponse = statisticsApi.getWorkViewData(params);
                if(null != mapResponse){
                    wapScenceDTO.setUv (Long.valueOf(String.valueOf(mapResponse.get("uv"))).longValue());
                    wapScenceDTO.setPv(Long.valueOf(String.valueOf(mapResponse.get("pv"))).longValue());
                    wapScenceDTO.setFpv(Long.valueOf(String.valueOf(mapResponse.get("fpv"))).longValue());
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        map.put("rows", resultList);
        map.put("total", wapScenceDTOList.size());
        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        return success().setMap(map);
    }


    public List<WapScenceDTO> dealScence(List<WapScenceDTO> wapScenceDTOList,Integer pageNo,Integer pageSize){
        int totalOrderSize =0;
        try{
            wapScenceDTOList.sort(new Comparator<WapScenceDTO>() {//Comparator 比较器. 需要实现比较方法
                public int compare(WapScenceDTO o1, WapScenceDTO o2) {
                    return o2.getUpdateTime().compareTo(o1.getUpdateTime());//时间降序
                }
            });
            logger.info("dealScence->{}",new Gson().toJson(wapScenceDTOList));
            //手动分页
            totalOrderSize = wapScenceDTOList.size();
            // 开始索引
            int fromIndex = (pageNo-1) * pageSize;
            // 结束索引
            int toIndex = fromIndex + pageSize;
            // 如果结束索引大于集合的最大索引，那么规定结束索引=集合大小
            if(toIndex > totalOrderSize){
                toIndex = totalOrderSize;
            }
            if(fromIndex <= totalOrderSize){
                return wapScenceDTOList.subList(fromIndex, toIndex);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
